import { login, getInfo, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    real_name: '',
    uid: 0,
    avatar: '',
    roles: [],
    is_super: null,
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_REAL_NAME: (state, real_name) => {
    state.real_name = real_name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_UID: (state, uid) => {
    state.uid = uid
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_SUPER: (state, is_super) => {
    state.is_super = is_super
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        // console.log('module:login:', response)
        const { token, expires } = response
        commit('SET_TOKEN', token)
        setToken(token, expires)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        if (!response) {
          return reject('校验失败, 请重新登录.')
        }

        const { id, name, real_name, is_superuser, avatar, roles } = response

        commit('SET_UID', id)
        commit('SET_NAME', name)
        commit('SET_REAL_NAME', real_name)
        commit('SET_AVATAR', avatar)
        commit('SET_ROLES', roles)
        commit('SET_SUPER', is_superuser)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise(async (resolve) => {
      const userInfo = {
        username: state.name
      }
      const res = await logout(userInfo)
      console.log("logout: ", res);

      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

